package org.example.testWebsocket.config;


import org.example.testWebsocket.interceptor.WebSocketInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    private final WebSocketInterceptor webSocketInterceptor;

    public WebSocketConfig(WebSocketInterceptor webSocketInterceptor) {
        this.webSocketInterceptor = webSocketInterceptor;
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws") // 修正：路径参数
                .addInterceptors(webSocketInterceptor) // 添加拦截器
                .setAllowedOriginPatterns("*") // 允许跨域
                .withSockJS();

        // 原生 STOMP 端点（无 SockJS），便于非 SockJS 客户端（如 Apifox、wscat）直接测试
        registry.addEndpoint("/ws-native")
                .addInterceptors(webSocketInterceptor)
                .setAllowedOriginPatterns("*");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic"); // 消息代理前缀
        registry.setApplicationDestinationPrefixes("/app"); // 应用请求前缀
    }
}
